<template>
  <div>
    <div>商家参与拼团活动列表</div>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入品牌名称"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadList">搜索</el-button>
          <el-button type="primary" @click="showAddActiveJoin"
            >添加拼团活动</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="joinId" label="ID" width="50" />
        <el-table-column prop="activeId" label="活动Id" width="50" />
        <el-table-column prop="joinName" label="拼团活动名称" width="100" />
        <el-table-column prop="joinDesc" label="活动描述" width="100" />
        <el-table-column prop="prodUnit" label="商品单位" width="100" />
        <el-table-column prop="images" label="商品轮播图" width="240">
          <template #default="scope">
            <el-image
              v-if="scope.row.images != null && scope.row.images != ''"
              v-for="item in scope.row.images"
              :src="item"
              :key="item"
              style="width: 50px; height: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="beginTime" label="开始时间" width="240" />
        <el-table-column prop="endTime" label="截止时间" width="240" />
        <el-table-column prop="expireTime" label="拼团时效" width="100" />
        <el-table-column prop="groupNum" label="拼团人数" width="100" />
        <el-table-column prop="buyMax" label="总购买数量限制" width="100" />
        <el-table-column prop="virtualNum" label="补齐人数 " width="100" />
        <el-table-column prop="prodInfoId" label="拼团商品" width="100" />
        <el-table-column prop="sendKind" label="配送方式" width="100" />
        <el-table-column prop="sendPay" label="运费设置" width="100" />
        <el-table-column prop="sendMoney" label="运费" width="100" />
        <el-table-column prop="joinTop" label="排序" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="240" />
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="JoinActiveshop(scope.row)"
              >参与拼团活动（商家参与）</el-button
            >
            <el-button type="primary" @click="onUpdateActiveJoin(scope.row)"
              >修改</el-button
            >
            <el-button type="primary" @click="onDeleteActiveJoin(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title" width="500">
        <el-form :model="addForm">
          <el-form-item label="拼团活动名称" :label-width="formLabelWidth">
            <el-input v-model="addForm.joinName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="拼团活动简介" :label-width="formLabelWidth">
            <el-input v-model="addForm.joinDesc" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品单位" :label-width="formLabelWidth">
            <el-select v-model="addForm.prodUnit" placeholder="请选择">
              <el-option
                v-for="item in prodUntiList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/prod/type/uploadImages"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="活动开始时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="addForm.beginTime"
              type="datetime"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="活动截止时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="addForm.endTime"
              type="datetime"
              placeholder="请先选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="拼团时效" :label-width="formLabelWidth">
            <el-input v-model="addForm.expireTime" autocomplete="off" />
          </el-form-item>
          <el-form-item label="拼团人数" :label-width="formLabelWidth">
            <el-input v-model="addForm.groupNum" autocomplete="off" />
          </el-form-item>
          <el-form-item label="总购买数量限制" :label-width="formLabelWidth">
            <el-input v-model="addForm.buyMax" autocomplete="off" />
          </el-form-item>
          <el-form-item label="补齐人数" :label-width="formLabelWidth">
            <el-input v-model="addForm.virtualNum" autocomplete="off" />
          </el-form-item>
          <el-form-item label="拼团商品" :label-width="formLabelWidth">
            <el-select v-model="addForm.prodInfoId" placeholder="请选择">
              <el-option
                v-for="item in prodList"
                :label="item.prodName"
                :value="item.prodId"
                :key="item.prodId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="配送方式" :label-width="formLabelWidth">
            <el-select v-model="addForm.sendKind" placeholder="请选择">
              <el-option label="快递" :value="1" />
              <el-option label="邮寄" :value="2" />
              <el-option label="自取" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="运费设置" :label-width="formLabelWidth">
            <el-input v-model="addForm.sendPay" autocomplete="off" />
          </el-form-item>
          <el-form-item label="运费" :label-width="formLabelWidth">
            <el-input v-model="addForm.sendMoney" autocomplete="off" />
          </el-form-item>
          <el-form-item label="排序" :label-width="formLabelWidth">
            <el-input v-model="addForm.joinTop" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              v-if="title == '添加商品活动列表'"
              type="primary"
              @click="onAddActiveJoin"
            >
              保存
            </el-button>
            <el-button
              v-if="title == '修改商品活动列表'"
              type="primary"
              @click="HandlerUpdateActiveJoin"
            >
              修改
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
const route = useRoute();
import { onMounted, reactive, ref } from "vue";
import {
  getGroupJoinList,
  getDictList,
  getprodListPage,
  addActiveJoin,
  updateActiveJoin,
  deleteActiveJoin,
  addActiveRecord,
} from "../api/api";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps, UploadUserFile } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const fileList = ref<UploadUserFile[]>([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const tableData = ref([]);
const total = ref(0);
const activeId = route.params.activeId;
console.log(activeId, "---------");
const headers = {
  token: sessionStorage.getItem("token"),
};
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});

const title = ref("添加商品活动列表");

const addForm = ref({
  activeId: null,
  beginTime: "",
  buyMax: null,
  createBy: "",
  createTime: "",
  endTime: "",
  expireTime: null,
  groupNum: null,
  joinDesc: "",
  joinId: null,
  joinImages: "",
  joinName: "",
  joinTop: null,
  prodInfoId: null,
  prodUnit: null,
  sendKind: null,
  sendMoney: null,
  sendPay: null,
  virtualNum: null,
  images: [],
});

const form = ref({
  pageNum: 1,
  pageSize: 999999,
});

const prodUntiList = ref([]);
const prodList = ref([]);

const JoinActiveshop = (row: any) => {
  addActiveRecord(row).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("参团成功");
      router.push("/home/joingroup");
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//删除商家参与活动
const onDeleteActiveJoin = (row: any) => {
  deleteActiveJoin(row.joinId).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//修改商家参与活动
const HandlerUpdateActiveJoin = () => {
  const imsss = [];
  fileList.value.forEach((item) => {
    console.log(item, "________________________-");

    if (item.url == undefined) {
      imsss.push(item.url);
    } else {
      imsss.push(item.response.data);
    }
  });
  addForm.value.images = imsss;
  updateActiveJoin(addForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//修改回显
const onUpdateActiveJoin = (row: any) => {
  fileList.value = [];
  title.value = "修改商品活动列表";
  console.log(row, "---------------");

  Object.assign(addForm.value, row);
  console.log(addForm.value, "==================");

  addForm.value.images.forEach((item) => {
    console.log(item, "=-=-=-=-=-==");

    let image = {};
    image.url = item;
    fileList.value.push(image);
  });

  dialogFormVisible.value = true;
};

//添加商家参与活动
const onAddActiveJoin = () => {
  let images: any = [];
  fileList.value.forEach((item) => {
    images.push(item.response.data);
  });
  addForm.value.images = images;
  addForm.value.activeId = activeId;
  addActiveJoin(addForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//显示添加活动参与框
const showAddActiveJoin = () => {
  title.value = "添加商品活动列表";
  addForm.value = {
    activeId: null,
    beginTime: "",
    buyMax: null,
    createBy: "",
    createTime: "",
    endTime: "",
    expireTime: null,
    groupNum: null,
    joinDesc: "",
    joinId: null,
    joinImages: "",
    joinName: "",
    joinTop: null,
    prodInfoId: null,
    prodUnit: null,
    sendKind: null,
    sendMoney: null,
    sendPay: null,
    virtualNum: null,
    images: [],
  };
  dialogFormVisible.value = true;
};

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};

//查询列表
const loadList = () => {
  getGroupJoinList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

//初始化数据
onMounted(() => {
  //获取商品列表
  getprodListPage(form.value).then((res) => {
    prodList.value = res.data.data.records;
  });

  //获取字典表数据
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      prodUntiList.value = res.data.data;
    }
  });

  loadList();
});

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
</script>

<style scoped></style>
